/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.pclong.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 *
 * @author Administrator
 */
public class ManageClassLoader {

    private DynamicClassLoader dc = null;
    private Long lastModified = 0l;
    private Class<?> c = null;

    /** 
     * 加载类， 如果类文件修改过加载，如果没有修改，返回当前的 
     * */
    public Class<?> loadClass(String fileName) throws ClassNotFoundException, IOException {
        if (isClassModified(fileName)) {
            dc = new DynamicClassLoader();
            c = dc.findClass(getBytes(fileName));
        }
        return c;
    }

    /** 
     * 判断是否被修改过 
     * */
    private boolean isClassModified(String fileName) {

        boolean returnValue = false;
        File file = new File(fileName);
        if (file.lastModified() > lastModified) {
            returnValue = true;
        }
        return returnValue;
    }

    /** 
     * 从本地读取文件 
     * */
    private byte[] getBytes(String fileName) throws IOException {
        File file = new File(fileName);

        long len = file.length();

        lastModified = file.lastModified();
        byte[] buf = new byte[(int) len];
        FileInputStream fis = new FileInputStream(file);
        int r = fis.read(buf);
        if (r != len) {
            throw new IOException("Can't read all, " + r + " != " + len);
        }
        fis.close();
        return buf;

    }

    public static void main(String[] args) throws ClassNotFoundException,
            IOException, InstantiationException,
            IllegalAccessException,
            SecurityException, NoSuchMethodException,
            IllegalArgumentException,
            InvocationTargetException,
            InterruptedException {

        String path = "d:\\hello.class";
        ManageClassLoader mc = new ManageClassLoader();
        Class<?> c = mc.loadClass(path);
// 创建实例 
        Object o = c.newInstance();
        Method m = c.getMethod("getName");
// 反射 
        m.invoke(o);
        System.out.println(c.getClassLoader());

    }
}
